package org.redmagic.location.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.redmagic.ResponseDecoder;

public class JsonResponseDecoder implements ResponseDecoder {

	private static final String MEDIA_TYPE = "application/json";
	private static final JsonFactory JSON_FACTORY = new JsonFactory();
	
	@Override
	public String getMediaType() {
		return MEDIA_TYPE;
	}
	
	@Override
	public Properties decode(InputStream response) {
		try {
			return tryDecode(response);
		} catch (Exception e) {
			throw new RuntimeException("Unable to decode response", e);
		}
	}

	private Properties tryDecode(InputStream response) throws JsonParseException, IOException {
		Properties properties = new Properties();
		
		JsonParser parser = JSON_FACTORY.createJsonParser(response);
		JsonToken token = parser.nextToken(); // Read off the START_OBJECT token
		while (token != null && (token = parser.nextToken()) != JsonToken.END_OBJECT) {
			parseProperty(properties, parser);
		}
		
		return properties;
	}
	
	private void parseProperty(Properties properties, JsonParser parser) throws JsonParseException, IOException {
		String key = parser.getText();
		String value = parser.nextTextValue();
		properties.put(key, value);
	}
}
